//@author A0106044W
package logic;

import java.util.logging.Level;

import commandInfo.AddCommandInfo;
import commandInfo.CommandInfo;
import commandInfo.RemoveCommandInfo;
import storage.Task;

/**
 * 
 * 
 * 	       Sothearith Sreang
 *         All of the Logic part is written by me.
 * 
 */

public class RemoveHandler extends OperationHandler {
	
	Task task;
	
	private static final String SUCCESSFUL_DELETE_MESSAGE = "The task with \"%s\" is successfully deleted";
	private static final String UNSUCCESSFUL_DELETE_MESSAGE = "task found in displayList cannot be found in storage. Check Storage and Logic who passes this task.";
	private static final String SUCCESSFUL_UNDO_MESSAGE = "The task with \"%s\" is now added";
	
	private static final String EXCEPTION_NULL_TASK_FOR_REMOVE = "Task in remove(Task) is null";
	private static final String EXCEPTION_NULL_TASK_FOR_ADD = "Task in add(Task) is null";
	
	// Two public constructors
	
	//for normal remove operation
	public RemoveHandler(Task taskAtt){
		super();
		task = taskAtt;
	}
	
	//for undo and remove remove operation
	public RemoveHandler(CommandInfo commandInfoP){
		super();
		setTask(commandInfoP);
	}
	
	
	// This method is called for user command's remove operation
	public String execute(){
		Task taskClone = getTaskClone();			
		assert taskClone != null;
		
		removeTask(taskClone);
		String feedback = String.format(SUCCESSFUL_DELETE_MESSAGE, taskClone.getDescription());
		
		return feedback;
	}

	// This method is called for undo for previous remove operation
	public String undo(){
		addTask();
		super.commandInfo = new AddCommandInfo(task);
		String feedback = String.format(SUCCESSFUL_UNDO_MESSAGE, task.getDescription());
		
		return feedback;
	}

	
	// next level abstraction
	
	void setTask(CommandInfo commandP){
		task = commandP.getPreviousTask();
	}
	
	private Task getTaskClone() {
		Task taskClone = null;	
		
		try{
			taskClone = task.cloneSelf();
		} catch (Exception e) {
			Logic.logger.log(Level.SEVERE, e.getMessage());
		}

		return taskClone;
	}
	
	private void removeTask(Task taskClone) {
		boolean isSuccess = false;
		
		try{
			
			isSuccess = storage.removeTask(task);
			if(isSuccess) {
				super.commandInfo = new RemoveCommandInfo(taskClone);
			} else {
				Logic.logger.log(Level.SEVERE, UNSUCCESSFUL_DELETE_MESSAGE);
			}
			
		} catch(Exception e) {
			Logic.logger.log(Level.SEVERE, EXCEPTION_NULL_TASK_FOR_REMOVE);
		}
	}
	
	private void addTask() {
		assert task != null;
		
		try{
			super.storage.addTask(task);
		} catch(Exception e) {
			Logic.logger.log(Level.SEVERE, EXCEPTION_NULL_TASK_FOR_ADD);
		}

	}
	
}
